var express = require("express")
var router = express()
var nunjucks = require("nunjucks")
var sql = require("../kit/sql.js")
var _ = require("ramda")
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

// SQLString -> (Error -> Rows -> Fields) -> ()
var esql = sql.esql
// SQL String -> [a] -> (Error -> Rows -> Fields) -> ()
var esqlp = sql.esqlp

nunjucks.configure('view', {
    autoescape: true,
    express: router,
    noCache:process.env.NOCACHE != "true"
});

router.use(bodyParser.urlencoded({ extended: false }));
router.use(cookieParser());

router.get("/",function(req,res){
  res.render("sswd/sswd.html")
})

router.post("/",function(req,res){
  var rn = parseInt(req.body.renshu)
  if(rn > 30){
    res.send("人数最大不能超过30")
    return;
  }
  var wdn = parseInt(rn/4)
  var xs = range1(rn).sort(function(a,b){return Math.random() > .5})

  esqlp("insert into sswd_t(dicts,total,cnum,wd) values(?,?,0,?)",
  [
    req.body.pingmin +"," + req.body.wodi,
    rn,
    _.take(wdn,xs).join(",")
  ],function(err,rows,fileds){
    res.redirect("/sswd/room/"+rows.insertId)
  })
})
router.get("/room-num/:roomid",function(req,res){
  esqlp("select cnum from sswd_t where roomid = ?",
  [parseInt(req.params.roomid)],
  function(err,rows){
    res.json(rows[0]&&rows[0].cnum)
  })
})

router.get("/room/:roomid",function(req,res){
  var roomid = parseInt(req.params.roomid);
  if(isNaN(roomid)){
    res.send("错误的地址")
    return null
  }
  esqlp("select dicts,total,cnum,wd from sswd_t where roomid = ?",
  [roomid],
  function(err,rows){
    if(rows.length == 0){
      res.send("房间不存在")
      return null
    }else{
      var item = rows[0]
      var roomidCode = parseInt(req.params.roomid)^7
      res.render("sswd/room.html",
      {
        item:item,
        roomid:req.params.roomid,
        roomidCode:roomidCode
      })
    }
  })
})

router.get("/room/:roomid/join",function(req,res){
  var room = req.cookies.xxx
  var proomid = parseInt(req.params.roomid)
  if(isNaN(proomid)){
    res.send("错误的地址")
    return null
  }
  var roomid = proomid^7
  if(room == roomid + ''){
    res.redirect(req.cookies["room-url"])
  }else{
    res.render("sswd/join.html")
  }
})
router.post("/room/:roomid/join",function(req,res){
  var room = req.cookies.xxx
  var proomid = parseInt(req.params.roomid)
  if(isNaN(proomid)){
    res.send("错误的地址")
    return null
  }
  var roomid = proomid^7
  if(room == roomid + ''){
    res.redirect(req.cookies["room-url"])
  }else{
    querySSWD(roomid,function(item){
      if(item == null){
        res.send("不存在的地址")
        return
      }
      if(item.cnum == item.total){
        res.send("人员已满")
        return null
      }
      updateSSWDCnum(roomid,item.cnum+1,function(){
        var iswd = _.any(function(a){
          return a == "" + (item.cnum+1)
        },item.wd.split(","))

        var dict = item.dicts.split(",")[0]
        if(iswd){
          dict = item.dicts.split(",")[1]
        }
        var url = "/sswd/"+(item.cnum+1)+"-"+dict
        res.cookie('xxx', roomid, {maxAge: 10* 60 * 1000})
        res.cookie('room-url', url, {maxAge: 10* 60 * 1000})
        res.redirect(url)
      })
    })
  }
})

router.get("/:msg",function(req,res){
  var msgs = req.params.msg.split("-")
  res.send("<h1>您是"+msgs[0]+"号，您的词语是:" + msgs[1]+"</h1>")
})
// RoomIDNumber -> CNumNumber -> (() -> ())
function updateSSWDCnum(roomid,cnum,fn){
  esqlp("update sswd_t set cnum = ? where roomid = ?",
  [cnum,roomid],
  function(err,rows){
    fn()
  })
}
// RoomIDNumber -> {} -> ({} -> ())
function querySSWD(roomid,fn){
  esqlp("select dicts,total,cnum,wd from sswd_t where roomid = ?",
  [roomid],
  function(err,rows){
    fn(rows[0])
  })
}
// Number -> [Number]
function range1(n){
  var r = []
  for(var i=1;i<=n;i++) r.push(i)
  return r
}
module.exports = router
